/**
 * Created by Administrator on 2015/10/9.
 */
var appFactory = angular.module('app.factory',['ionic','ngCordova']);

appFactory.factory('DB',['$q','$cordovaSQLite','$cordovaToast','DB_CONFIG',function($q,$cordovaSQLite,$cordovaToast,DB_CONFIG){
  var db = null;
  var init = function(){
    if(!window.cordova) {
      db = $cordovaSQLite.openDB({name: DB_CONFIG.name});
    }else{
      db = window.sqlitePlugin.openDatabase({name: DB_CONFIG.name});
    }
    DB_CONFIG.tables.forEach(function(table){
      var columns = [];
      table.columns.forEach(function(column){
        columns.push(column.name + ' ' + column.type);
      });
      var sql = 'create table if not exists ' +table.name+'('+columns.join(',')+')';
      console.log('Table '+table.name+' initialized');
      query(sql);
    });
  };

  //判断是不是第一次登陆
  var isFistLogin = function(callback){
    var sql = 'select * from users;';
    $cordovaSQLite.execute(db, sql, []).then(function(res){
      if(res.rows.length>0){
        callback(true);
      }else{
        callback(false);
      }
    },function(err){
      callback(false);
    });
  }

  var query = function(sql,bindings){
    bindings = typeof bindings != 'undefined'? bindings:[];
    return $cordovaSQLite.execute(db,sql,bindings);
  };

  var insert = function(table,columns,valus){
    var sqls = '';
    if(table!=null && '' != table){
      sqls += 'insert into '+ table +'('+columns.join(',')+')';
      sqls += ' values (';
      for(var i = 0;i<valus.length;i++){
        sqls += '"'+valus[i]+'"';
        if(i < valus.length-1){
          sqls += ',';
        }else{
          sqls += ') ';
        }
      }
      $cordovaSQLite.execute(db, sqls, []).then(function(res){
        //$cordovaToast.showLongTop('数据成功插入'+res.result);
      },function(err){
        $cordovaToast.showLongTop('数据插入失败'+err);
      });
    }
  }

  var executeSql = function(sql,bindings,callback,flag){
    var output = [];
    $cordovaSQLite.execute(db, sql, []).then(function(res){
      //$cordovaToast.showLongTop('查询成功。'+ res.rows.length);
      for(var  i = 0;i<res.rows.length;i++){
        output.push(res.rows.item(i));
      }
      if(output.length>0){
        callback(flag,output);
      }
    },function(err){
      $cordovaToast.showLongTop('数据查询失败：'+sql);
    });
  };

  var updateSql = function(sql,bindings,callback){
    var output = [];
    $cordovaSQLite.execute(db, sql, []).then(function(res){
      for(var  i = 0;i<res.rows.length;i++){
        output.push(res.rows.item(i));
      }
      if(output.length>0){
        if(callback!=null){
          callback(output);
        }
      }
    },function(err){
      $cordovaToast.showLongTop('数据更新失败：'+sql);
    });
  }

  var fetchAll = function(result){
    var output = [];
    for(var  i = 0;i<result.rows.length;i++){
      output.push(result.rows.item(i));
    }
    return output;
  };

  var fetch = function(result){
    return result.rows.item(0);
  };

  return {
    init:init,
    query:query,
    fetchAll:fetchAll,
    fetch:fetch,
    insert:insert,
    executeSql : executeSql,
    updateSql : updateSql,
    isFistLogin:isFistLogin
  };

}]);

